package com.jerry.base.thread;

import lombok.extern.slf4j.Slf4j;

/**
 * Created with IntelliJ IDEA
 * User: Jerry
 * Date: 2024/2/22
 * Time: 22:00
 * Description:
 */
public class DeadLock {

    public static void main(String[] args) throws InterruptedException {
        Dead dead = new Dead(true);
        dead.setName("线程1");
        Dead dead2 = new Dead(false);
        dead2.setName("线程2");

        dead.start();
        dead2.start();
    }

}

@Slf4j
class Dead extends Thread {

    static Object o = new Object();
    static Object o2 = new Object();

    private boolean flag;

    Dead(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        if (flag) {
            synchronized (o) {
                log.info("{}拿到了o的锁，等待获取o2的锁", Thread.currentThread().getName());
                synchronized (o2) {
                    log.info("拿到了o2的锁");
                }
            }
        } else {
            synchronized (o2) {
                log.info("{}拿到了o2的锁，等待获取o的锁", Thread.currentThread().getName());
                synchronized (o) {
                    log.info("拿到了o的锁");
                }
            }
        }
    }
}
